package cn.hnu.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;

@Service
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发送简单文本邮件
     */
    public void sendSimpleEmail(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("3334175026@qq.com"); // 发件人
        message.setTo(to); // 收件人
        message.setSubject(subject); // 主题
        message.setText(text); // 内容
        mailSender.send(message);
    }

    /**
     * 发送HTML格式邮件
     */
    public void sendHtmlEmail(String to, String subject, String htmlContent) 
            throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        message.setFrom("3334175026@qq.com"); // 发件人

        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(htmlContent, true); // true表示内容是HTML
        
        mailSender.send(message);
    }

    /**
     * 发送考试相关邮件示例
     */
    public void sendExamNotification(String studentEmail, String studentName, 
                                   String examName, String examTime) {
        String subject = "考试通知 - " + examName;
        String text = String.format(
            "亲爱的 %s 同学：\n\n" +
            "您已成功报名参加《%s》考试。\n" +
            "考试时间：%s\n\n" +
            "请提前做好准备，祝您考试顺利！\n\n" +
            "海南大学在线考试系统",
            studentName, examName, examTime
        );
        
        sendSimpleEmail(studentEmail, subject, text);
    }
}